<template>
    <el-card>
        <template #header>
            个人中心
        </template>
        <el-row class="card-content" :gutter="20">
            <el-col :span="4">
                <div class="avatar-wrapper">
                    <el-upload class="avatar-uploader"
                               :before-upload="beforeAvatarUpload"
                               action="http://localhost:8501/admin/system/fileUpload"
                               :show-file-list="false"
                               :on-success="handleAvatarSuccess" :headers="headers">
                        <el-avatar :src="userInfo.avatar" size="large"></el-avatar>
                    </el-upload>
                    <el-button type="info" size="small" style="margin-top: 10px" :disabled="!canUpdateAvatar"
                               @click="updateUserAvatar">
                        确定更新
                    </el-button>
                </div>
            </el-col>
            <el-col :span="20">
                <div class="user-details">
                    <p><strong>id:</strong> {{ userInfo.id }}</p>
                    <p><strong>用户名:</strong> {{ userInfo.username }}</p>
                    <p><strong>邮箱:</strong> {{ userInfo.email }} </p>
                    <p><strong>手机号:</strong>
                        <el-input size="small" type="text" v-model="maskedMobile" disabled style="width: 130px"/>
                        <el-button type="text" size="small" @click="updateMobile">
                            {{ maskedMobile ? '去验证' : '去绑定' }}
                        </el-button>
                    </p>
                    <p v-if="userInfo.status==1"><strong>状态:</strong> 正常 </p>
                    <p><strong>最近一次登录时间:</strong> {{ userInfo.lastLoginTime }}</p>
                    <p><strong>最后一次登录地址:</strong> {{ userInfo.ipconf }}</p>
                </div>
            </el-col>
        </el-row>
    </el-card>
    <el-dialog v-model="dialogFormVisible" title="更换绑定手机号" width="40%">
        <el-form :model="form" label-width="140px" :rules="rules">
            <el-form-item label="手机号" prop="phone">
                <el-input v-model="form.phone" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="手机验证码" prop="code">
                <el-input v-model="form.code" placeholder="请输入验证码" style="width: 70%"/>
                <el-button type="primary" style="width: 25%;margin-left: 1%;" @click="sendVerificationCode"
                           :disabled="countdown > 0">
                    {{ countdown > 0 ? countdown + 's后重新发送' : '发送验证码' }}
                </el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="updatePhoneNumber">确定</el-button>
                <el-button @click="dialogFormVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>
<script setup>
import {useAccount} from "@/pinia/modules/account";
import {SendVerificationCode, UpdateMobile, UpdateUserAvatar} from "@/api/sysUser";
import {useApp} from "@/pinia/modules/app";
import {ElMessage} from "element-plus";
import {computed, ref} from "vue";

// 使用 useAccount 存储模块  获取用户信息
const userInfo = useAccount().userinfo;
// 使用计算属性处理手机号，只显示部分数字
const maskedMobile = computed(() => {
    const mobile = userInfo.mobile;
    return mobile ? mobile.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '';
});
const canUpdateAvatar = ref(false); // 初始化标志位为 false，表示禁止更新头像
const headers = {
    token: useApp().authorization.token, // 从pinia中获取token，在进行文件上传的时候将token设置到请求头中
}
const beforeAvatarUpload = (file) => {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
    }
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!');
    }
    return isJPG && isLt2M;
}
// 处理上传成功后的回调
const handleAvatarSuccess = async (response) => {
    if (response.code === 200) {
        ElMessage.success('上传成功')
        userInfo.avatar = response.data;
        canUpdateAvatar.value = true;
    } else {
        ElMessage.error('上传失败,请检查文件格式！')
    }

};
const updateUserAvatar = async () => {
    const {code} = await UpdateUserAvatar(userInfo.id, userInfo.avatar, useApp().authorization.token);
    if (code == 200) {
        ElMessage.success('头像更新成功')
        canUpdateAvatar.value = false;
    }
}
const dialogFormVisible = ref(false);
const updateMobile = () => {
    dialogFormVisible.value = true
};
const form = ref({
    phone: '',
    code: ''
});
const rules = {
    phone: [
        {required: true, message: '请输入手机号', trigger: 'blur'},
        {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
    ],
    code: [
        {required: true, message: '请输入验证码', trigger: 'blur'},
        {pattern: /^\d{6}$/, message: '请输入6位数字验证码', trigger: 'blur'}
    ]
}
let countdown = ref(0);
let timer = null;
// 更新手机号的方法
const updatePhoneNumber = async () => {
    const {code} = await UpdateMobile(userInfo.username, form.value.phone, form.value.code, useApp().authorization.token);
    if (code == 200) {
        ElMessage.success('手机号更新成功')
        dialogFormVisible.value = false;
        userInfo.mobile = form.value.phone;
    }
}

// 发送验证码的方法
const sendVerificationCode = async () => {
    const {code} = await SendVerificationCode(form.value.phone);
    if (code != 200) {
        ElMessage.error('验证码发送失败')
        return;
    }
    ElMessage.success('验证码已发送,5分钟内有效');
    // 开始倒计时
    startCountdown();
};

// 开始倒计时
const startCountdown = () => {
    countdown.value = 60;
    timer = setInterval(() => {
        countdown.value--;
        if (countdown.value === 0) {
            clearInterval(timer);
        }
    }, 1000);
};

</script>

<style scoped>
.card-content {
    padding: 20px;
}

.user-details {
    padding-left: 20px;
}

.avatar-wrapper {
    margin: auto;
    display: flex;
    flex-direction: column; /* 垂直排列 */
    align-items: center; /* 水平居中 */
    justify-content: center;
}
</style>